﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using KsWare.Breconium.Core;
using Ksx.KoCTool.Data;

namespace Ksx.KoCTool.Tabs.Reports {

	/// <summary> Interaction logic for Reports.xaml
	/// </summary>
	public partial class Reports {
		private int mTotalPages;

		public Reports() {
			InitializeComponent();
		}

		private void GetReportsClick(object sender, RoutedEventArgs e) {
			if(((App)Application.Current).Server.DefaultSession==null) {
				MessageBox.Show("No connection availabe.\r\n(Still connecting?)");
				return;
			}
			mReportListView.ItemsSource = null;
			var reports	 = new List<ReportVM>();
			var page = 0;
			while (true) {
				if(!ReadPage(page,reports))break;
				page++;
			}
			mReportListView.ItemsSource = reports;
			//App.SetStatus("Done Load Reports pages "+"("+mTotalPages+").");
		}

		private bool ReadPage(int page, List<ReportVM> reports) {
			App.SetStatus("Load Reports page "+(page+1)+"("+mTotalPages+")...");

			ListReportData result = null;

			var ajax = new AjaxRequestData {
				method="post",
				url="ajax/listReports.php",
				parameters = new ListReportsParameters {
					pageNo = page, 
					@group = "a"
				}
			};
			var cmd = new Command("ajaxrequest", ajax);
			var tries = 0;
			while (true) {
				tries++;
				App.SetStatus("Load Reports page "+(page+1)+"("+mTotalPages+") try "+(tries)+"...");

				try {((App)Application.Current).Server.DefaultSession.ExecuteCommand(cmd,TimeSpan.FromSeconds(30));} 
				catch (Exception ex) {
					Trace.WriteLine("Reports ReadPage Error "+ex.GetType().Name + " "+ ex.Message);
					continue;
				}
				result=ParseListReportsData(cmd.Result);
				if(!result.ok) {
					App.Trace("Reports.ReadPage: ok=False");
				} else if(result.ok && result.error_code!=null) {
					App.Trace("Reports.ReadPage: error_code="+result.error_code);
				} else {
					break;
				}
			}

			if (!result.ok) {
				return false;
			} 
			var totalPages = result.totalPages;
			mTotalPages = (int) totalPages;
			foreach (var kp in result.arReports) {
				var report = kp.Value;
				var vm = new ReportVM();
				vm.Page = page + 1;
				vm.Id = report.reportId;
				vm.Timestamp = new DateTime(new DateTime(1970, 1, 1).AddSeconds(report.reportUnixTime).Ticks).ToString("yyyy-MM-dd HH:mm:ss");
				vm.Side0Coord = (report.side0XCoord + "," + report.side0YCoord);
				vm.Side0PlayerId = report.side0PlayerId.ToString();
				vm.Side0PlayerGender = report.side0PlayerId > 0 ? result.arPlayerNames["g" + report.side0PlayerId] : "";
				vm.Side0PlayerName = report.side0PlayerId > 0 ? result.arPlayerNames["p" + report.side0PlayerId] : "";
				vm.Side0AllianceId = report.side0AllianceId.ToString();
				vm.Side0AllianceName = report.side0AllianceId > 0 ? result.arAllianceNames["a" + report.side0AllianceId] : "";
				vm.Side0CityId = report.side0CityId;
				vm.Side0CityName = report.side0CityId > 0 ? result.arCityNames["c" + report.side0CityId] : "";
				vm.Side1Coord = (report.side1XCoord + "," + report.side1YCoord);
				vm.Side1PlayerId = report.side1PlayerId.ToString();
				vm.Side1PlayerGender = report.side1PlayerId > 0 ? result.arPlayerNames["g" + report.side1PlayerId] : "";
				vm.Side1PlayerName = report.side1PlayerId > 0 ? result.arPlayerNames["p" + report.side1PlayerId] : "";
				vm.Side1AllianceId = report.side1AllianceId.ToString();
				vm.Side1AllianceName = report.side1AllianceId > 0 ? result.arAllianceNames["a" + report.side1AllianceId] : "";
				vm.MarchType = ParseMarchType(long.Parse(report.marchType), 1).ToString();
				vm.MarchTypeState = report.marchTypeState;
				reports.Add(vm);
			}
			return page + 1 < totalPages;
		}

		private ListReportData ParseListReportsData(Json result) { 
			// {ok=True, error_code=9, data={}}

			var data=new ListReportData();
			
			data.ok=result.Bool("ok")==true;
			if(!data.ok) return data;
			data.error_code = result.String("error_code");
			if(data.error_code!=null) return data;
			data.totalPages = result.Long("totalPages",0);
			data.arReports=new Dictionary<string, ListReportItemData>();
			foreach (string kp in result.Path("arReports").Keys) {
				var report = result.Path("arReports." + kp);
				data.arReports.Add(kp,new ListReportItemData{
					reportType     = report.String("reportType"),
					reportId       = report.String("reportId"),
					reportUnixTime = report.Long ("reportUnixTime",0),
					side0XCoord    = report.String("side0XCoord"),
					side0YCoord    = report.String("side0YCoord"),
					side0TileType  = report.String("side0TileType"),
					side0TileLevel = report.String("side0TileLevel"),
					side0CityId    = report.Long  ("side0CityId",0),
					side0PlayerId  = report.Long  ("side0PlayerId",0),
					side0AllianceId= report.Long  ("side0AllianceId",0),
					side1XCoord    = report.String("side1XCoord"),
					side1YCoord    = report.String("side1YCoord"),
					side1CityId    = report.Long  ("side1CityId",0),
					side1PlayerId  = report.Long  ("side1PlayerId",0),
					side1AllianceId= report.Long  ("side1AllianceId",0),
					marchType      = report.String("marchType"),
					marchTypeState = report.String("marchTypeState"),
					reportStatus   = report.String("reportStatus"),
				});
			}
			data.arPlayerNames=new Dictionary<string, string>();
			foreach (KeyValuePair<string,object> kp in result.Path("arPlayerNames")) {
				data.arPlayerNames.Add(kp.Key,kp.Value.ToString());
			}
			data.arCityNames=new Dictionary<string, string>();
			foreach (KeyValuePair<string,object> kp in result.Path("arCityNames")) {
				data.arCityNames.Add(kp.Key,kp.Value.ToString());
			}
			data.arAllianceNames=new Dictionary<string, string>();
			foreach (KeyValuePair<string,object> kp in result.Path("arAllianceNames")) {
				data.arAllianceNames.Add(kp.Key,kp.Value.ToString());
			}
			return data;
		}

		private KocMarchType ParseMarchType(long marchType,long sideId) {
			if (marchType == 0) return KocMarchType.Desertion;
			else if (marchType == 1) return KocMarchType.Transport;
			else if (marchType == 2) return KocMarchType.Reinforced;
			else if (marchType == 3 || marchType == 11) {
				if (sideId == 0) return KocMarchType.AntiScout;
				else return KocMarchType.Scout;
			} else if (marchType == 4) {
				if (sideId == 0)return KocMarchType.Defense;
				else return KocMarchType.Attack;
			} else if (marchType == 10 || marchType == 9) {
				return KocMarchType.Attack;
			} else
				return KocMarchType.Unknown;
		}

	}

	class ListReportsParameters:IAjaxRequestParameters {
		public int pageNo { get; set; }
		public string group { get; set; } // "a" - alliance
	}

	public enum KocMarchType {
		Desertion=0,
		Transport=1,
		Reinforced=2,
		AntiScout=3,
		Scout=11,

		Defense=4,
		Attack=402,
		Attack9=9,
		Attack10=10,
		Unknown=99,
	}

//	getRpt: function (pageNum){
//		var t = Tabs.Rpt;
//		var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
//		params.pageNo = pageNum;
//		if (Options.rptType == 'alliance')
//			params.group = "a";
//		new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/listReports.php" + unsafeWindow.g_ajaxsuffix, {
//			method: "post",
//			parameters: params,
//			onSuccess: function (rslt){
//				t.getRptCallback (rslt, pageNum);
//			},
//			onFailure: function (rslt){
//				t.getRptCallback (rslt, pageNum);
//			},
//		}, false);
//	},
//	getRptCallback: function(rslt, page){
//		var t = Tabs.Rpt;
//		if (rslt) {
//			if (!rslt.ok) {
//				ById("idRptStatus").innerHTML = '<FONT color=#ffaaaa>' + rslt.errorMsg + '</FONT>';
//				return;
//			}
//			t.totalPages=parseInt(rslt.totalPages);
//			if (t.totalPages < t.maxPages)
//				t.maxPages = t.totalPages;
//			if (rslt.arReports && page) {
//				var ar = rslt.arReports;
//				//if (ar.length == 0)
//				//t.stopSearch('Page vide trouve depuis la page ' + page + ' - Kabam glitch');
//				var rptkeys = unsafeWindow.Object.keys(ar);
//				for (var i = 0; i < rptkeys.length; i++) {
//					var rpt = ar[rptkeys[i]];
//					var reportId = parseInt(rpt.reportId);
//					t.report[reportId] = [];
//					t.report[reportId].side1Name = rslt.arPlayerNames['p'+rpt.side1PlayerId];
//					t.report[reportId].side1AllianceId = parseInt(rpt.side1AllianceId);
//					if (rpt.side1AllianceId > 0)
//						t.report[reportId].side1AllianceName = rslt.arAllianceNames['a'+rpt.side1AllianceId];
//					else
//						t.report[reportId].side1AllianceName = '-';
//					if (rpt.side1CityId > 0)
//						t.report[reportId].side1CityName = rslt.arCityNames['c'+rpt.side1CityId];
//					else
//						t.report[reportId].side1CityName = '-';
//					t.report[reportId].side1XCoord = rpt.side1XCoord;
//					t.report[reportId].side1YCoord = rpt.side1YCoord;
//					if (parseInt(rpt.side0PlayerId) == 0) { // Kabam
//						t.report[reportId].side0Name = ''+culang.reportEnemy+'';
//						t.report[reportId].side0AllianceName = '';
//						t.report[reportId].side0CityName = '';
//					} else {
//						t.report[reportId].side0Name = rslt.arPlayerNames['p'+rpt.side0PlayerId];
//						if (rpt.side0AllianceId > 0)
//							t.report[reportId].side0AllianceName = rslt.arAllianceNames['a'+rpt.side0AllianceId];
//						else
//							t.report[reportId].side0AllianceName = '-';
//						if (rpt.side0CityId > 0)
//							t.report[reportId].side0CityName = rslt.arCityNames['c'+rpt.side0CityId];
//						else
//							t.report[reportId].side0CityName = '-';
//					}
//					t.report[reportId].side0AllianceId = parseInt(rpt.side0AllianceId);
//					t.report[reportId].side0XCoord = rpt.side0XCoord;
//					t.report[reportId].side0YCoord = rpt.side0YCoord;
//					if (parseInt(rpt.side0TileType) == 10)
//						t.report[reportId].side0TileTypeText=culang.kocGrassland;
//					else if (parseInt(rpt.side0TileType) == 11)
//						t.report[reportId].side0TileTypeText=culang.kocLake;
//					else if (parseInt(rpt.side0TileType) == 20)
//						t.report[reportId].side0TileTypeText=culang.kocForests;
//					else if (parseInt(rpt.side0TileType) == 30)
//						t.report[reportId].side0TileTypeText=culang.kocHill;
//					else if (parseInt(rpt.side0TileType) == 40)
//						t.report[reportId].side0TileTypeText=culang.kocMount;
//					else if (parseInt(rpt.side0TileType) == 50)
//						t.report[reportId].side0TileTypeText=culang.kocPlain;
//					else if (parseInt(rpt.side0TileType) == 51 && parseInt(rpt.side0CityId) == 0)
//						t.report[reportId].side0TileTypeText=culang.mainCity;
//					else if (parseInt(rpt.side0TileType) == 54)
//						t.report[reportId].side0TileTypeText=culang.shortDarkForest;
//					else if (parseInt(rpt.side0CityId) == 0)
//						t.report[reportId].side0TileTypeText=culang.kocShortBarbarian;
//					else
//						t.report[reportId].side0TileTypeText=culang.mainCity;
//
//
//
//
//					t.report[reportId].side0TileTypeLevel = t.report[reportId].side0TileTypeText + ' ' + rpt.side0TileLevel;
//					t.report[reportId].side0TileType = rpt.side0TileType;
//					t.report[reportId].side0TileLevel = rpt.side0TileLevel;
//					t.report[reportId].page = page;
//					t.report[reportId].reportUnixTime = rpt.reportUnixTime;
//					if (rpt.side0AllianceId == parseInt(getMyAlliance()[0]))
//						t.report[reportId].sideId = 0;
//					else if (rpt.side1AllianceId == parseInt(getMyAlliance()[0])) {
//						t.report[reportId].sideId = 1;
//					} else {
//						if (rpt.side0PlayerId == getMyUserId())
//							t.report[reportId].sideId = 0;
//						else if (rpt.side1PlayerId == getMyUserId())
//							t.report[reportId].sideId = 1;
//						else
//							t.report[reportId].sideId = -1;
//					}
//					if (!ById("KsSyntheseAttack").checked && parseInt(rpt.side0TileType) == 54 && Options.rptType=='player') {
//						t.FindItemRpt(reportId, t.report[reportId].sideId, t.report[reportId].side0TileLevel);
//					}
//					if (ById("KsSyntheseAttack").checked && (rpt.marchType == 4 || rpt.marchType == 3))
//					{
//						t.KsSyntheseAttack(reportId, t.report[reportId].sideId, 0);
//					}
//
//					if (rpt.marchType == 0)
//						t.report[reportId].marchName = culang.mainDesertion;
//					else if (rpt.marchType == 1)
//						t.report[reportId].marchName = culang.mainTransport;
//					else if (rpt.marchType == 2)
//						t.report[reportId].marchName = culang.mainReinforced;
//					else if (rpt.marchType == 3 || rpt.marchType == 11) {
//						if (t.report[reportId].sideId == 0)
//							t.report[reportId].marchName = culang.mainAntiScout;
//						else
//							t.report[reportId].marchName = culang.mainScout;
//					} else if (rpt.marchType == 4) {
//						if (t.report[reportId].sideId == 0)
//							t.report[reportId].marchName = culang.mainDefense;
//						else
//							t.report[reportId].marchName = culang.mainAttack;
//					} else if (rpt.marchType == 10 || rpt.marchType == 9) {
//						t.report[reportId].marchName =  culang.mainAttack;
//					} else
//						t.report[reportId].marchName = '?';
//					t.data.push ({
//						reportId: reportId,
//					});
//				}
//			}
//			if (parseInt(page)+1 <= t.maxPages && t.searchRunning) {
//				ById("idRptStatus").innerHTML = culang.reportSearchedPages+' ' + (parseInt(page)+1) + ' / ' + t.maxPages;
//				t.getRpt(parseInt(page)+1);
//				if (t.data.length > 0)
//					t.DisplayRpt();
//			} else if (page) {
//
//				if (ById("KsSyntheseAttack").checked) {
//					t.stopSearch ('<a id=KsresumeAT style="color:#ffaaaa" onclick="javascript:void(0);"><u>'+culang.reportAttackSummary+'</u></a>');
//					setTimeout(function() {
//						// ouverture du resume des rapports FS avec Items
//						ById("KsresumeAT").addEventListener ('click', t.AfficheResumeAtk, false);
//					}, 1000);
//				} else {
//
//					if (Options.rptType=='player') {
//						t.stopSearch ('<a id=KsresumeDF style="color:#ffaaaa" onclick="javascript:void(0);"><u>'+culang.reportDarkForestSummary+'</u></a>');
//						setTimeout(function() {
//							// ouverture du resume des rapports FS avec Items
//							ById("KsresumeDF").addEventListener ('click', t.AfficheResume, false);
//						}, 1000);
//					} else {
//						t.stopSearch (''+culang.mainHDone+'');
//					}
//				}
//			}
//		}
//	}
}
